#version 430

uniform mat4 u_proj;
uniform mat4 u_view;
uniform mat4 u_model;
uniform vec3 u_eyepos;
uniform vec3 u_earth2sun;//from earth point to sun
uniform mat4 u_invtprojview; // invert of proj*view
uniform float u_near;

in vec2 ndcposi; // position in NDC near plane
out vec4 fragColor;

vec3 sun_color = vec3(1.0, 0.7, 0.55);

//both neyedir and nsundir should be normalized
vec3 render_sky_color(vec3 neyedir, vec3 nsundir){
	float sun_amount = max(dot(neyedir, nsundir), 0.0);
	vec3  sky = mix(vec3(.0, .1, .4), vec3(.3, .6, .8), 1.0 - neyedir.y);
	sky = sky + sun_color * min(pow(sun_amount, 1500.0) * 5.0, 1.0);
	sky = sky + sun_color * min(pow(sun_amount, 10.0) * 0.6, 1.0);
	return sky;
}

void main()
{
	vec4 npwp = u_invtprojview * vec4(ndcposi.xy * u_near, -u_near, u_near);//near plane world position
	vec3 neyedir = normalize(npwp.xyz - u_eyepos);
	//npwp = npwp / npwp.w;
	//vec3 neyedir = normalize(eyedir);
	vec3 skycolor = render_sky_color(neyedir, u_earth2sun);
	fragColor = vec4(skycolor, 1.0);

	//fragColor = vec4(npwp.x, 0.0 , 0.0 , 1.0);
}



